import { ref, reactive, computed, watch, onMounted } from 'vue'
import type { Drama } from '../api/drama'
import { getAllDramas } from '../api/drama'

// 字幕状态过滤选项枚举
export enum SubtitleStatusFilter {
  ALL = 'all',        // 全部显示
  COMPLETED = 'completed',  // 只显示已完成
  INCOMPLETE = 'incomplete' // 只显示未完成
}

export function useDramaList() {
  const searchQuery = ref('')
  const loading = ref(false)
  const allDramas = ref<Drama[]>([])
  const error = ref<string | null>(null)
  
  // 字幕状态过滤
  const subtitleStatusFilter = ref<SubtitleStatusFilter>(SubtitleStatusFilter.ALL)
  
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索相关状态
  const isSearchMode = ref(false)
  const searchTotal = ref(0)
  const lastSearchTime = ref(0)

  // 获取所有剧集数据
  const fetchAllDramas = async () => {
    if (loading.value) return
    
    loading.value = true
    error.value = null
    
    try {
      console.log('🎬 开始获取所有剧集数据...')
      const startTime = Date.now()
      
      const dramas = await getAllDramas()
      
      // 确保数据是数组并按ID排序
      const sortedDramas = Array.isArray(dramas) 
        ? dramas.sort((a, b) => a.id - b.id)
        : []
      
      allDramas.value = sortedDramas
      pagination.total = sortedDramas.length
      
      const loadTime = Date.now() - startTime
      console.log(`✅ 剧集数据加载完成: ${sortedDramas.length}条记录, 耗时${loadTime}ms`)
      
    } catch (err) {
      console.error('❌ 获取剧集数据失败:', err)
      error.value = err instanceof Error ? err.message : '获取数据失败'
      allDramas.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 过滤搜索和字幕状态结果
  const filteredDramas = computed(() => {
    let dramas = allDramas.value

    // 先进行字幕状态过滤
    if (subtitleStatusFilter.value !== SubtitleStatusFilter.ALL) {
      dramas = dramas.filter(drama => {
        if (subtitleStatusFilter.value === SubtitleStatusFilter.COMPLETED) {
          return drama.subtitleStatus === 0
        } else if (subtitleStatusFilter.value === SubtitleStatusFilter.INCOMPLETE) {
          // null、undefined 或者不等于0的都算未完成
          return drama.subtitleStatus !== 0
        }
        return true
      })
    }

    // 再进行搜索过滤
    if (!searchQuery.value.trim()) {
      return dramas
    }

    const keyword = searchQuery.value.trim().toLowerCase()
    const startTime = Date.now()
    
    const filtered = dramas.filter(drama => {
      // 搜索ID (支持数字搜索)
      if (drama.id.toString().includes(keyword)) {
        return true
      }
      
      // 搜索标题
      if (drama.title && drama.title.toLowerCase().includes(keyword)) {
        return true
      }
      
      return false
    })
    
    const searchTime = Date.now() - startTime
    searchTotal.value = filtered.length
    lastSearchTime.value = searchTime
    
    return filtered
  })

  // 当前页显示的数据
  const displayedDramas = computed(() => {
    const filtered = filteredDramas.value
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    
    return filtered.slice(start, end)
  })

  // 计算总页数
  const totalPages = computed(() => {
    // 使用过滤后的数据量计算总页数
    const total = filteredDramas.value.length
    return Math.ceil(total / pagination.pageSize)
  })

  // 获取过滤后的总数（用于分页显示）
  const filteredTotal = computed(() => {
    return filteredDramas.value.length
  })

  // 处理搜索
  const handleSearch = () => {
    const hasQuery = searchQuery.value.trim().length > 0
    
    if (hasQuery !== isSearchMode.value) {
      isSearchMode.value = hasQuery
      pagination.currentPage = 1 // 重置到第一页
    }
    
    console.log(`🔍 搜索: "${searchQuery.value}", 结果: ${searchTotal.value}条`)
  }

  // 清除搜索
  const clearSearch = () => {
    searchQuery.value = ''
    isSearchMode.value = false
    pagination.currentPage = 1
    searchTotal.value = 0
    lastSearchTime.value = 0
  }

  // 设置字幕状态过滤
  const setSubtitleStatusFilter = (filter: SubtitleStatusFilter) => {
    subtitleStatusFilter.value = filter
    pagination.currentPage = 1 // 重置到第一页
    console.log(`🏷️ 字幕状态过滤: ${filter}`)
  }

  // 处理分页变化
  const handlePageChange = () => {
    console.log(`📄 切换到第${pagination.currentPage}页 (每页${pagination.pageSize}条)`)
  }

  // 重置状态
  const reset = () => {
    searchQuery.value = ''
    pagination.currentPage = 1
    pagination.pageSize = 20
    allDramas.value = []
    subtitleStatusFilter.value = SubtitleStatusFilter.ALL
    clearSearch()
    error.value = null
  }

  // 监听搜索查询变化
  watch(searchQuery, () => {
    handleSearch()
  })

  // 监听字幕状态过滤变化
  watch(subtitleStatusFilter, () => {
    pagination.currentPage = 1 // 重置到第一页
    console.log(`🎯 字幕状态过滤变更: ${subtitleStatusFilter.value}, 过滤后总数: ${filteredTotal.value}`)
  })

  // 监听分页变化，确保当前页不超出范围
  watch([totalPages, () => pagination.currentPage], ([newTotalPages, currentPage]) => {
    if (currentPage > newTotalPages && newTotalPages > 0) {
      pagination.currentPage = newTotalPages
    }
  })

  // 组件挂载时获取数据
  onMounted(() => {
    fetchAllDramas()
  })

  return {
    // 状态
    searchQuery,
    loading,
    searchLoading: computed(() => false), // 前端搜索不需要loading
    isSearchMode,
    pagination,
    error,
    subtitleStatusFilter,
    
    // 计算属性
    displayedDramas,
    searchTotal,
    lastSearchTime,
    totalPages,
    filteredTotal,
    
    // 方法
    fetchDramasPage: fetchAllDramas, // 兼容现有调用
    handleSearch,
    handlePageChange,
    clearSearch,
    setSubtitleStatusFilter,
    reset,
    refreshData: fetchAllDramas,
    
    // 枚举导出
    SubtitleStatusFilter
  }
}